package com.mao.server.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mao.server.constant.Constants;
import com.mao.server.domain.po.User;
import com.mao.server.exception.ServiceException;
import com.mao.server.mapper.UserMapper;
import com.mao.server.utils.TokenUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class LoginService extends ServiceImpl<UserMapper, User> {
    @Resource
    UserMapper userMapper;

    public User selectByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.USERNAME, username);
        return getOne(queryWrapper);
    }

    public User login(User user) {
        loginPrecheck(user.getUsername(), user.getPassword());
        User dbUser = selectByUsername(user.getUsername());
        if (dbUser == null) {
            throw new ServiceException(Constants.ACCOUNT_NOT_FOUND);
        }
        if (!user.getPassword().equals(dbUser.getPassword())) {
            throw new ServiceException(Constants.PASSWORD_NOT_MATCH);
        }
        // 生成token
        String token = TokenUtil.createToken(dbUser);
        dbUser.setToken(token);
        return dbUser;
    }

    private void loginPrecheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            throw new ServiceException(Constants.USERNAME_OR_PASSWORD_NULL);
        }
        // 用户名不在指定范围内 错误
        if (username.length() < Constants.USERNAME_MIN_LENGTH || username.length() > Constants.USERNAME_MAX_LENGTH) {
            throw new ServiceException(Constants.USER_USERNAME_NOT_MATCH);
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < Constants.PASSWORD_MIN_LENGTH || password.length() > Constants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException(Constants.USER_PASSWORD_NOT_MATCH);
        }
    }
}
